<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\controller\Util;
use think\Db;
use think\Env;
use think\Exception;
use think\Hook;
use app\common\library\Sms;
use app\common\model\User;
class Bizstudent extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['studentRegister','getCompetitiveList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * Notes:学生注册接口/注册即登录
     * User: XingLiangRen
     * Date: 2020/8/17
     * Time: 10:16
     */
    public function studentRegister()
    {
        $param = $this->checkPhoneUser();
        // 验证验证码的正确
        $smsResult =  Sms::check($param['phone'],$param['code'],'register');
        $smsResult ?: $this->error("手机号或验证码错误");
        if($user = User::get(['mobile' => $param['phone']])){
            if(!empty($param['code'])){
                $this->auth->direct($user->id);
            }else{
                $this->auth->login($param['phone'], $param['password']);
            }
            $this->success('登陆成功',$this->auth->getUserinfo());
        }
        $initStudentName = '学生'.Util::getInviteCode();
        // 用户表注册
        $ret = $this->auth->register($initStudentName, 00000000, '', $param['phone'], ['group_id' => 4]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $params['invite_code'] = Util::getInviteCode();
            $params['user_id'] = $data['userinfo']['user_id'];
            $params['register_time'] = date("Y-m-d H:i:s");
            $params['phone'] = $param['phone'];
            $params['point'] = !Env::get('distribution.student_register') ? 0 :Env::get('distribution.student_register_num', '10');
            $student_id = Db::name('student')->insert($params,false,true);
            if(!empty($param['by_invite_code'])){
//                 注册im信息
                $im_data = [
                    'name' => $initStudentName,
                    'uid'  => $student_id,
                    'type' => 'student',
                ];
                $data = Hook::listen("createAccountForUser",$im_data,'',true);
//                 分销模块
                $hooks_data = [
                    'student_id' => $student_id,
                    'by_invite_code' => $param['by_invite_code'],
                ];
                Hook::listen("calculatePoint",$hooks_data);
            }
            if(empty($student_id)){
                Db::name('user')->where('id',$params['user_id'])->delete();
                $this->error("注册失败");
            }
            $this->success(__('Sign up successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * Notes:完善学生信息
     * User: XingLiangRen
     * Date: 2020/8/17
     * Time: 11:57
     */
    public function perfectStudentInfo(){
        $param['nick_name'] = input('nickname');
        $param['header_image'] = input('header_image');
        $param['sex'] = input('sex');
        $param['age'] = input('age');
        $param['user_name'] = input('user_name');
        $param['english_name'] = input('english_name');
        $param['birthday'] = input('birthday');
        $param['address'] = input('address');
        $param['grade'] = input('grade');
        $param['school'] = input('school');
        $user_id = $this->auth->id;
        // 启动事务
        $flag = true;
        Db::startTrans();
        try{
            Db::name("student")->where("user_id",$user_id)->update($param);
            $userData['id'] = $user_id;
            $userData['username'] = $param['user_name'];
            $userData['nickname'] = $param['nick_name'];
            $userData['avatar'] = $param['header_image'];
            $userData['birthday'] = $param['birthday'];
            Db::name('user')->update($userData);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
          return $this->success("完善成功");
    }


    /**
     * Notes:获取学生信息
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 15:44
     */
    public function getStudentInfo(){
        $data = Db::name('student')->where('id',$this->getUid())->find();
        $this->success('查询成功',$data);
    }
    /**
     * Notes:重置密码
     * User: XingLiangRen
     * Date: 2020/8/25
     * Time: 11:24
     */
    public function resetPassword(){
        $newpassword = $this->request->post("newpassword");
        if (!$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->changepwd($newpassword, '', true);
        $ret ? $this->success('重置密码成功') : $this->error();
    }

    /**
     * Notes:添加收货地址
     * User: XingLiangRen
     * Date: 2020/8/25
     * Time: 18:16
     */
    public function addAddress(){
        $param =  $this->AddressValidate();
        $insertData = [
            'uid'  => $this->getUid(),
            'type' => 'student',
            'name' => $param['name'],
            'mobile' => $param['mobile'],
            'city' => $param['city'],
            'address' => $param['address'],
        ];
        $result =  Db::name('address')->insert($insertData);
        $result ? $this->success("保存成功") : $this->error("系统繁忙");
    }

    /**
     * Notes:删除地址
     * User: XingLiangRen
     * Date: 2020/8/27
     * Time: 18:55
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function delAddress(){
        $id = $this->request->post('id');
        if(empty($id)){
            $this->error('缺少参数');
        }
        $result =  Db::name('address')->where('id',$id)->delete();
        $result ? $this->success("删除成功") : $this->error("系统繁忙");
    }
    /**
     * Notes:收货地址列表
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 10:00
     */
    public function addressList(){
        $data = Db::name('address')->where(['type'=>'student','uid' => $this->getUid()])->field(['uid','type'],true)->select();
        $this->success("查询成功",$data);
    }
    private function AddressValidate(){
        $param = $this->request->post();
        // 数据校验
        $data = $this->validate($param, [
            'name'     => 'require',
            'mobile'    => 'require|regex:/^1[3456789]\d{9}$/',
            'city'     => 'require',
            'address'  => 'require',
        ], [
                'name.require'        => '收货人必填',
                'mobile.require'      => '手机号码必填',
                'mobile.regex'        => '手机号码格式错误',
                'city.require'        => '所在地区必填',
                'address.require'     => '详细地址必填',
            ]
        );
        if (!empty($data) && $data !== true) {
            $this->error($data);
        }
        return $param;
    }
    /**
     * Notes:修改收货地址
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 10:12
     */
    public function editAddress(){
        $param =  $this->AddressValidate();
        $insertData = [
            'name' => $param['name'],
            'mobile' => $param['mobile'],
            'city' => $param['city'],
            'address' => $param['address'],
        ];
        $result =  Db::name('address')->where('id',$param['id'])->update($insertData);
        $result ? $this->success("保存成功") : $this->error("没有信息发生改变");
    }

    /**
     * Notes:修改手机号
     * User: XingLiangRen
     * Date: 2020/8/28
     * Time: 11:57
     */
    public function changeMobile(){
        $param = $this->request->post();
        // 数据校验
        $data = $this->validate($param, [
            'phone'    => 'require|regex:/^1[3456789]\d{9}$/',
            'code'     => 'regex:/^\d{6}$/',
        ], [
                'phone.require'     => '手机号码必填',
                'phone.regex'       => '手机号码格式错误',
                'code.regex'        => '验证码格式错误',
            ]
        );
        if (!empty($data) && $data !== true) {
            $this->error($data);
        }
        $smsResult =  Sms::check($param['phone'],$param['code'],'changemobile');
        $smsResult ?: $this->error("验证码错误");
        $result = Db::name('user')->where(['mobile'=>['=',$param['phone']],'id'=>['<>',$this->auth->id]])->find();
        Util::checkEmpty($result,'array') ? $this->error('该手机号已注册') : '';
        if( $this->auth->getUser()->salt !== '0' &&
            $this->auth->getUser()->password !== $this->auth->getEncryptPassword($param['password'],$this->auth->getUser()->salt)){
            $this->error('密码错误');
        }
        Db::startTrans();
        try {
            Db::name('user')->where('id',$this->auth->id)->update(['mobile'=>$param['phone']]);
            Db::name('student')->where('id',$this->getUid())->update(['phone'=>$param['phone']]);
            Db::commit();
            $this->success('修改成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * Notes:查看课程是否被购买
     * User: XingLiangRen
     * Date: 2020/9/1
     * Time: 11:09
     */
    public function checkCourseOrderStatus(){
        $course_id = $this->request->get('course_id');
        $res = Db::name('order')->where(['userId'=>$this->getUid(),'courseId'=>$course_id,'status'=>['in',['paid','lock','created']]])->find();
        if($res){
            if($res['status'] == 'paid'){
                $this->error('您已购买过此课程,请勿重复购买',['status' => '1']);
            }elseif ($res['status'] == 'created'){
                $this->error('您的订单已生成,请前往购物车支付',['status' => '2']);
            }
        }
        $this->success('未购买此订单',['status' => '0']);
    }
    /**
     * Notes:我的购买课程
     * User: XingLiangRen
     * Date: 2020/9/1
     * Time: 17:53
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myBuysCourses(){
        $field = 't.nick_name,t.header,c.id,c.title,c.subtitle,c.tache,c.duration,c.difficulty,c.cover_image,c.section_num,c.expiry_start_time,c.expiry_end_time,c.type_status,c.lived_course_lesson_id';
        $type = $this->request->get("type");
        if(Util::checkEmpty($type) && $type == 'simple'){
            $field = 'c.id,c.title';
        }
        $data = Db::name('order')->alias('o')
                    ->join('course c','o.courseId = c.id','LEFT')
                    ->join('teacher t', 'c.teacher_id = t.id','LEFT')
                    ->where(['userId'=>$this->getUid(),'status'=>'paid'])
                    ->field($field)
                    ->select();
        if(!Util::checkEmpty($type) && $type != 'simple'){
            foreach ($data as &$v) {
                $count = Db::name('course_lesson_learn')->where(['user_id' => $this->getUid(), 'course_id' => $v['id']])->count();
                $v['plan'] = 0;
                if ($count !== 0) {
                    if($v['section_num'] !== 0){
                        $v['plan'] = round($count / $v['section_num'],2);
                    }
                }
                $v['count'] = $count;
                $lesson_id = \db('course_lesson_learn')->where(['user_id' => $this->getUid(), 'course_id' => $v['id']])->max('lesson_id');
//                $lesson_title = Db::name('course_lesson')->where('id', $lesson_id)->field('title')->find();
//                $v['lesson_title'] = $lesson_title['title'] ?? "暂无学习课程";
                $v['max_lesson_id'] = $lesson_id;
                //如果没有学习课程则给返回第一节课
                if($v['max_lesson_id'] == 0){
                   $lesson =  Db::name('course_lesson')->where('course_id',$v['id'])->order('lesson_id','ASC')->find();
                   if(!empty($lesson)){
                       $v['max_lesson_id'] = $lesson['id'];
                   }
                }
                if($v['type_status'] == '1'){
                    //查看该播哪节课了
                    $lesson_id = Db::name('course_lesson')->where('id',$v['lived_course_lesson_id'])->find();
                    if(!empty($lesson_id)){
                        $lesson_id = $lesson_id['lesson_id'] + 1;
                    }else{
                        $lesson_id = 1;
                    }
                    $course_lesson = Db::name('course_lesson')
                        ->where(['course_id' => $v['id'],'lesson_id' => $lesson_id,'lesson_type' => 'live'])
//                                                ->whereTime('start_time','<=',time())
//                                                ->whereTime('end_time','>=',time())
                        ->field(['id','room_id','start_time','end_time','play_status'])
                        ->find();
                    $v['course_lesson'] = $course_lesson;
                 }
            }
        }
        $this->success('查询成功',$data);
    }

    /**
     * Notes:添加学习记录
     * User: XingLiangRen
     * Date: 2020/9/17
     * Time: 10:51
     */
    public function addStudyLog(){
        $courseLessonId = input('courseLessonId');
        $courseId = Db::name('course_lesson')->where('id',$courseLessonId)->field('course_id')->find()['course_id'];
        if(empty($courseId)){
            $this->error("错误的章节");
        }
        $userId = $this->getUid();
        $where = ['user_id' => $userId,'course_id' => $courseId, 'lesson_id' => $courseLessonId];
        $data = [
            'start_time' => time(),
        ];
        $ret = Db::name('course_lesson_learn')->where($where)->find();
        if(!empty($ret)){
            //更新
            $updateData =  array_merge($where,['id'=>$ret['id'],'update_time' => time()]);
            Db::name('course_lesson_learn')->inc('watch_num')->update($updateData);
        }else{
            $insterData =  array_merge($where,['update_time' => time(),'start_time' => time(),'watch_num' => 1]);
            Db::name('course_lesson_learn')->insert($insterData);
        }
    }

    /**
     * Notes:精品课程列表
     * User: XingLiangRen
     * Date: 2020/9/7
     * Time: 9:44
     */
    public function getCompetitiveList(){
        $grade_id = input('grade_id','1');
        $where = ['is_check' => 2, 'is_issue' => 1, 'grade_id' => $grade_id];
        if(!empty($this->auth->id)){
            $grade_id = Db::name('student')->where('user_id',$this->auth->id)->field('grade')->find()['grade'];
            if(!empty($grade_id)){
                $where['grade_id'] = $grade_id;
            }
        }
        $data = Db::name('course')->where($where)->field('id,cover_image,title')->order('hit_num DESC')->limit(0,2)->select();
        $this->success('查询成功',$data);
    }

    private function checkPhoneUser(){
        $param = $this->request->post();
        // 数据校验
        $data = $this->validate($param, [
            'phone'    => 'require|regex:/^1[3456789]\d{9}$/',
            'code'     => 'regex:/^\d{6}$/',
            'password' => 'regex:/^[0-9a-z_.]{8,16}$/i',
        ], [
                'phone.require'     => '手机号码必填',
                'phone.regex'       => '手机号码格式错误',
                'code.regex'        => '验证码格式错误',
                'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
            ]
        );
        if (!empty($data) && $data !== true) {
            $this->error($data);
        }
        return $param;
    }
    /**
     * Notes:获取课程详情(只有购买过的课程的学生才可以看)
     * User: XingLiangRen
     * Date: 2020/9/16
     * Time: 16:08
     */
    public function getCourseLesson(){
        $courseLessonId = input('courseLessonId');
        if(empty($courseLessonId)){
            $this->error('courseId is empty');
        }
        $studentId = $this->getUid();
        //查看学生是否购买了此课程
        $res = Db::name('course_lesson')->alias('cl')
                        ->join('order o','cl.course_id = o.courseId')
                        ->join('course c','cl.course_id = c.id')
                        ->join('teacher t','t.id = c.teacher_id')
                        ->where(['o.userId' => $studentId,'o.status' => 'paid','cl.id' => $courseLessonId])
                        ->field('cl.*,t.header,t.nick_name')
                        ->find();
        if(empty($res)){
            $this->error('您尚未购买此课程');
        }
        $this->success('查询成功',$res);
    }

    /**
     * Notes: 获取章节资源
     * User: XingLiangRen
     * Date: 2020/9/16
     * Time: 16:49
     */
    public function  getCourseLessonResource(){
        $courseLessonId = input('courseLessonId');
        if(empty($courseLessonId)){
            $this->error('courseId is empty');
        }
        $data = Db::name('course_lesson_resource')
                        ->where(['lesson_id' => $courseLessonId])
                        ->field('id,name,location')
                        ->select();
        $this->success('查询成功',$data);
    }

    /**
     * Notes:领取优惠券
     * User: XingLiangRen
     * Date: 2020/9/18
     * Time: 15:00
     */
    public function drawDiscount(){
        $courseId = input('courseId');
        $course = Db::name('course')->where('id',$courseId)->find();
        if(empty($course)){
            $this->error("课程不存在");
        }
        $uid = $this->getUid();
        //先看用户有没有领取过
        $ret = Db::name('coupon_user')->where(['course_id' => $courseId, 'uid' => $uid])->find();
        if($ret){
            $this->error('您已经领取过该优惠券');
        }
        //没有领取过to领取
        $data = [
            'name'        => '课程专属卷',
            'uid'         =>  $uid,
            'money'       =>  $course['discount'],
            'create_time' =>  date("Y-m-d H:i:s"),
            'start_time'  =>  date("Y-m-d H:i:s"),
            'end_time'    =>  date("Y-m-d H:i:s",time() + $course['discount_indate'] * 3600),
            'course_id'   => $courseId,
            'type'        => 1
        ];
        $res = Db::name('coupon_user')->insert($data);
        if($res){
            $this->success("领取成功");
        }
        $this->error("系统繁忙");
    }
    public function getInviteCode(){
        $baseUrl = Env::get('app.baseUrl');
        $student = Db::name('student')->where('user_id',$this->auth->id)->find();
        return Util::qrcode($baseUrl . '?code=' . $student['invite_code']);
    }

    /**
     * Notes:获取分销记录
     * User: XingLiangRen
     * Date: 2020/9/21
     * Time: 15:13
     */
    public function getInvestLog(){
        $uid = $this->getUid();
        //获取所有的下级id
        $firstID = Db::name('invest')->where(['role' => 'student', 'uid' => $uid])->select();
        $secondID = [];
        if(!empty($firstID)){
            foreach ($firstID as $v){
                $secondId = Db::name('invest')->where(['role' => 'student', 'uid' => $v['uid']])->select();
                $secondID = array_merge($secondID,$secondId);
            }
        }
        $allStudent = array_unique(array_column(array_merge($firstID,$secondID),'id'));
        $data = Db::name('invest_earnings')
                                    ->where(['invest_id'=>['in',$allStudent]])
                                    ->field('id,earnings,create_time,type')
                                    ->select();
        $this->success('查询成功',$data);
    }

    /**
     * Notes:获取我的消息
     * User: XingLiangRen
     * Date: 2020/9/25
     * Time: 11:09
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMyNotices()
    {
        $notices = Db::name('notices')->where(['to_role' => 'student', 'to_id' => $this->getUid()])->order('created_time DESC,is_read ASC')->select();
        if(!empty($notices)){
            foreach ($notices as &$v){
                $v['content'] = mb_substr($v['content'],0,18,'utf-8') . '...';
            }
        }
        $this->success('查询成功',$notices);
    }
    public function getNoticesContent(){
        $id = input('id');
        $notice = Db::name('notices')->where('id',$id)->find();
        Db::name('notices')->where('id',$id)->update(['is_read' => 1]);
        $this->success('查询成功',$notice);
    }
    public function delNotice(){
        $id = input('id');
        $notice = Db::name('notices')->where('id',$id)->delete();
        $this->success('删除成功');
    }

    /**
     * Notes:获取学生购物车总数
     * User: XingLiangRen
     * Date: 2020/9/26
     * Time: 14:27
     */
    public function getCarSum(){
        $count = Db::name('order_car_item')->where('student_id',$this->getUid())->count();
        $this->success('查询成功',$count);
    }
    /**
     * Notes:根据user_id获取studentID
     * User: XingLiangRen
     * Date: 2020/8/26
     * Time: 10:03
     */
    private function getUid(){
        return Db::name('student')->where('user_id',$this->auth->id)->field('id')->find()['id'];
    }
}